package router

import (
	"temp/api"
	"temp/cache"
	"temp/config"
	"temp/db"

	"temp/middleware"

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

func InitRouter(config config.Config) *gin.Engine {
	router := gin.Default()
	router.Use(gin.Recovery(), gin.Logger())
	router.Use(middleware.Cors())

	// 添加Swagger路由
	router.GET("/swagger/*any", ginSwagger.WrapHandler(
		swaggerFiles.NewHandler(),
	))

	initDB, err := db.InitDB(config.DB)
	if err != nil {
		panic(err)
	}
	cacheClient := cache.InitCache(config.Redis)

	userApi := api.NewUserApi(initDB, cacheClient)

	deptApi := api.NewDeptApi(initDB, cacheClient)

	// 无需认证的路由
	public := router.Group("/api/v1")
	{

		public.POST("/login", userApi.Login)
		public.POST("/register", userApi.Register)
	}

	// 需要认证的路由
	private := router.Group("/api/v1")
	private.Use(middleware.Auth())
	user := private.Group("/user")
	{
		user.GET("/current", userApi.CurrentUser)
		user.POST("/logout", userApi.Logout)
	}
	dept := private.Group("/dept")
	{
		dept.GET("/:id", deptApi.Detail)
	}

	return router
}
